import { QueryClient, useQuery } from 'react-query';
import { dehydrate } from 'react-query/hydration'
import Layout from "@/components/layout";
import HomeCourseNav from "@/components/home-course-nav";
import { getCourses } from "@/apis/course";

function CourseNavs() {
    const { data: courses } = useQuery('courses', getCourses);

    // group all courses by category
    let result = {};
    for (let c of courses) {
        if (!result[c.category]) {
            result[c.category] = {};
            result[c.category]['data'] = [];
            result[c.category]['views'] = 0;
        }
        result[c.category]['data'].push(c);
        result[c.category]['views'] += c.views;
    }

    // sort all course category by views number
    const sortedNav = Object.fromEntries(
        Object.entries(result).sort(([, a], [, b]) => b['views'] - a['views'])
    );

    // show course by category
    let CourseNavs = [];
    Object.keys(sortedNav).map((category) => (
        CourseNavs.push(
            <HomeCourseNav key={category} category={category} courses={result[category]['data']} views={result[category]['views']}></HomeCourseNav>
        )
    ));

    return (
        <div className="d-grid gap-4">
            {CourseNavs}
        </div>
    );

}

export default function HomePage() {

    return (
        <Layout title="Home">
            <CourseNavs></CourseNavs>
        </Layout>
    );
}

export async function getStaticProps(context) {
    const queryClient = new QueryClient()

    await queryClient.prefetchQuery('courses', getCourses)

    return {
        props: {
            dehydratedState: dehydrate(queryClient),
        },
    }
}
